<?php
/**
 * PHP Mortgage Calculator
 *
 * Copyright 2002-2008 Dave Tufts <davetufts@gmail.com>
 *
 * @version 2.0.0
 *
 * @author  Dave Tufts [dt] <davetufts@gmail.com>
 *
 * @changes 2.0.0 Major refactoring and code cleanup; added customizable property tax, assessed value, condo fee [dt, 2008-03-15]
 * @changes 1.3.0 Updated CSS [dt, 2007-08-21]
 * @changes 1.2.1 fixed bug with uninitialize variable $pmi_per_month, $pmi_text [dt, 2007-01-04]
 * @changes 1.2.0 fixed bug with number_format, clead up comments [dt, 2006-02-16]
 * @changes 1.1.0 initial release [dt, 2003-01-01]
 */













/* --------------------------------------------------------------------- */
/* HEADER (only printed if the output buffer is empty)
/* --------------------------------------------------------------------- */
	if (!headers_sent()) {
		?>
		<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
            "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
		<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
		<head>
			<meta http-equiv="content-type" content="text/html; charset=utf-8" />
			<style type="text/css" media="all">
				html {
					font-size: 84%;
				}
				body {
					width: 60em;
					margin: 2em auto;
					font: normal normal normal 1em/1.7em verdana,sans-serif; 
				}
				h1 { 
					background-color: #000;
					color: #fff;
					font-family: Helvetica,arial,sans-serif;
					font-size: 3em;
					margin: 0 -.5em;
					padding: .5em;
				}
			</style>
			
			<title>PHP Mortgage Calculator</title>
		</head>
		<body>
		
		<h1>PHP Mortgage Calculator</h1>

		<?php
		$print_footer = TRUE;
	} else {
		$print_footer = FALSE;
	}
?>




<?
/* --------------------------------------------------------------------- */
/* CSS
/* --------------------------------------------------------------------- */
?>





<?
/* --------------------------------------------------------------------- */
/* HTML OPENING
/* --------------------------------------------------------------------- */
?>
<div id="mortgage_calculator">





<?
/* --------------------------------------------------------------------- */
/* VALIDATION, CALCULATION
/* --------------------------------------------------------------------- */
?>
<?php		
try {
	if (!$form_complete) {
		throw new IncompleteException();
	}
	
	// validation
	if (($year_term <= 0) || ($sale_price <= 0) || ($mortgage_interest_percent <= 0)) {
		throw new Exception ( 'You must enter a <strong>Sale Price</strong>, <strong>Length of Mortgage</strong> and <strong>Annual Interest Rate</strong>');
	}
	if ($assessed_value <= 0 && $sale_price > 0) {
		$assessed_value = $sale_price * .85;
	}
	
	
	
	/* --------------------------------------------------------------------- */
	/* KEY CALCULATIONS
	/* --------------------------------------------------------------------- */

	// financing & down payment numbers
	

	/* --------------------------------------------------------------------- */


	
} catch (IncompleteException $e) {
	$form_complete = false;

} catch (Exception $e) {
	$form_complete = false;
	echo '<div class="error">' . $e->getMessage() . '</div>';
}
?>








<?php
/* --------------------------------------------------------------------- */
/* INFO - mortgage payment information
/* --------------------------------------------------------------------- */
?>
<?php if ($form_complete) { ?>






<?php
/* --------------------------------------------------------------------- */
/* CALCULATIONS - explanation of the calculations
/* --------------------------------------------------------------------- */
?>
<?php if ($form_complete) { ?>
	
	<h2>Calculations</h2>
	<p>
		To figure out the monthly payment, we need to know (1) how much 
		you're financing; (2) your monthly interest rate; and (3) how many 
		months you're financing for.
	</p>
	<p>
		Financials are typically quoted in yearly or annual numbers – <em>a 
		30-year mortgage or a 6% annual interest</em>. However, you pay your 
		mortgage every month. A lot of the calculations involve translating 
		those yearly numbers to their monthly equivalents.
	</p>
	<div class="calculation">
		<h3>1. Financing Price</h3>
		<p>
			First, we need to figure how much you're financing.
		</p>
		<p>
			We can do this based on the sale price of the home 
			(<strong><?php echo _money($sale_price); ?></strong>) and the 
			percent that you put down (<strong><?php echo $down_percent; ?>%</strong>).
		</p>
		<p>
			Start by calculating the down payment. Divide the percentage down by 100, 
			then multiply by the sale price of the home.
		</p>
		<p>
			(<?php echo $down_percent; ?>% / 100) x <?php echo _money($sale_price); ?> = 
			<strong><?php echo _money($down_payment); ?></strong>, 
			<em>your down payment</em>
		</p>
		<p>
			Now we can calculate how much you're financing – how much 
			you need to borrow. That's just the sale price minus your down payment.
		</p>
		<p class="result">
			<?php echo _money($sale_price); ?> - <?php echo _money($down_payment); ?> = 
			<strong><?php echo _money($financing_price); ?></strong>, 
			<em>your financing price</em>
		</p>
	</div>
	<div class="calculation">
		<h3>2. Monthly Interest Rate</h3>
		<p>
			That <strong><?php echo $mortgage_interest_percent; ?>%</strong> 
			interest rate percentage you secured is an <em>annual</em> percent.
		</p>
		<p>
			We'll need to convert that from a percentage to a decimal rate, 
			and from an annual representation to a monthly one.
		</p>
		<p>
			First, let's convert it to a decimal, by dividing the percent by 100.
		</p>
		<p>
			<?php echo $mortgage_interest_percent; ?>% / 100 = 
			<strong><?php echo $annual_interest_rate; ?></strong>, 
			<em>the annual interest rate</em>
		</p>
		<p>
			Now convert the annual rate to a monthly rate by dividing by 12 
			(for 12 months in a year).
		</p>
		<p class="result">
			<?php echo $annual_interest_rate; ?> / 12 = 
			<strong><?php echo $monthly_interest_rate; ?></strong>, 
			<em>your monthly interest rate</em>
		</p>
	</div>
	<div class="calculation">
		<h3>3. Month Term</h3>
		<p>
			Now for an easy calculation – the <strong>month term</strong>. 
			That's just the number of months you'll be paying off your loan.
		</p>
		<p class="result">
			You have a <?php echo $year_term; ?> year mortgage x 12 months = 
			<strong><?php echo $month_term; ?> months</strong>, 
			<em>your month term</em>.
		</p>
	</div>
	<div class="calculation">
		<h3>Final: Your Monthly Mortgage Payment</h3>
		<p>
			Using the three numbers above, we can now calculate your monthly payment.
		</p>
		<p>
			(financing price) x (monthly interest rate / (1 - ((1+monthly interest rate)<sup>-(monthly term)</sup>)))
		</p>
		<p class="result">
			<?php echo _money($financing_price); ?> x (<?php echo number_format($monthly_interest_rate, '4', '.', ''); ?> / (1 - ((1 + <?php echo number_format($monthly_interest_rate, '4', '.', ''); ?>)<sup>-(<?php echo $month_term; ?>)</sup>))) = <strong><?php echo _money($monthly_payment); ?></strong>, <em>your monthly payment*</em>
		</p>
		<p>
			*<em>Principal &amp; Interest only</em>. See 
			<a href="#total_payment">total monthly payment</a> for a your 
			mortgage plus taxes, insurance, and fees. See 
			<a href="#amortization">amortization</a> for a breakdown of how 
			each monthly payment is split between the bank's interest and 
			paying off the loan principal.
		</p>
	</div>
<?php } ?>





<?php
/* --------------------------------------------------------------------- */
/* AMORTIZATION - month by month breakdown of payments
/* --------------------------------------------------------------------- */
?>
<?php if ($form_complete) { ?>
	
	<?php
		// Set some base variables
		$principal	                 = $financing_price;
		$current_month               = 1;
		$current_year                = 1;
		$this_year_interest_paid     = 0;
		$this_year_principal_paid    = 0;
		$total_spent_over_term       = 0;

		// Re-figures out the monthly payment.
		$power = -($month_term);
		$denom = pow((1 + $monthly_interest_rate), $power);
		$monthly_payment = $principal * ($monthly_interest_rate / (1 - $denom));
		
		// This LEGEND will get reprinted every 12 months
		$legend  = '<tr class="legend">';
		$legend .= '<td>Month</td>';
		$legend .= '<td>Interest Paid</td>';
		$legend .= '<td>Principal Paid</td>';
		$legend .= '<td>Remaining Balance</td>';
		$legend .= '</tr>';
	?>

	<a name="amortization"></a>
	<h2>Amortization</h2>
	<p>
		Amortization for monthly payment, <?php echo _money($monthly_payment) ?>, 
		over <?= $year_term ?> years. Mortgage amortization only includes your 
		monthly principal and interest payments. Property taxes, PMI, and 
		condo fees are ignored when amortizing your mortgage.
	</p>
	<table cellpadding="0" cellspacing="0" class="amortization">
	
		<?php echo $legend; ?>
					
		<?php
			// Get the current month's payments for each month of the loan 
			while ($current_month <= $month_term) {	
				
				$interest_paid	          = $principal * $monthly_interest_rate;
				$principal_paid           = $monthly_payment - $interest_paid;
				$remaining_balance        = $principal - $principal_paid;
				$this_year_interest_paid  = $this_year_interest_paid + $interest_paid;
				$this_year_principal_paid = $this_year_principal_paid + $principal_paid;
				$show_legend              = ($current_month % 12) ? false : true;
			
				$total_spent_over_term    = $total_spent_over_term + ($interest_paid + $principal_paid);
				
				?>
		
				<tr>
					<td><?= $current_month ?></td>
					<td><?= _money($interest_paid) ?></td>
					<td><?= _money($principal_paid) ?></td>
					<td><?= _money($remaining_balance) ?></td>
				</tr>
		
				<?php if ($show_legend) { ?>
					<tr class="year_summary">
						<td colspan="4">
							<strong>Year <?php echo $current_year ?> Summary:</strong> 
							<span class="coaching">
								You spent <?php echo _money($this_year_interest_paid + $this_year_principal_paid) ?>
							</span>
							<p>
								<?php echo _money($this_year_principal_paid) ?> went to principal 
								<span class="coaching">This is equity that your building up</span>
								<br />
								
								<?php echo _money($this_year_interest_paid) ?>  went to interest 
								<span class="coaching">This is typically tax deductible</span>
							</p>
						</td>
					</tr>
					<?php
						$current_year++;
						$this_year_interest_paid  = 0;
						$this_year_principal_paid = 0;
			
						if (($current_month + 6) < $month_term) {
							echo $legend;
						}
					?>
				<?php } ?>
			
			<?php
			$principal = $remaining_balance;
			$current_month++;
		}
		?>
		<tr class="total_summary">
			<td colspan="4">
				Principal &amp; interest costs for the full  
				<?php echo $year_term ?> years of this mortgage total&hellip;
				<span class="total_spent_over_term"><?php echo _money($total_spent_over_term) ?></span>
			</td>
		</tr>	
	</table>
<?php } ?>





<?
/* --------------------------------------------------------------------- */
/* DESCRIPTION
/* --------------------------------------------------------------------- */
?>
<p>
	This mortgage calculator can be used to figure out monthly payments of a 
	home mortgage loan. This calculator automatically factors in 
	<acronym title="Private Mortgage Insurance">PMI</acronym> for loans 
	where less than 20% is put as a down payment. Also taken into 
	consideration are the town property taxes based on the mortgaged 
	property's assessed valued.
</p>
<p>
	The code for PHP Mortgage Calculator is free and can probably be 
	downloaded from <a href="http://www.davetufts.com/">http://davetufts.com</a>
</p>





<?
/* --------------------------------------------------------------------- */
/* HTML CLOSING
/* --------------------------------------------------------------------- */
?>
</div> <!-- closes #mortgage_calculator -->






<?
/* --------------------------------------------------------------------- */
/* FOOTER (only printed if header was printed)
/* --------------------------------------------------------------------- */
?>
<?php
	if ($print_footer) {
		echo '</body>';
		echo '</html>';
	}
?>





<?php
/* --------------------------------------------------------------------- */
/* FUNCTIONS
/* --------------------------------------------------------------------- */

/**
 * Calculates actual mortgage calculations by plotting a PVIFA table
 * (Present Value Interest Factor of Annuity)
 *
 * @param  float  length, in years, of mortgage
 * @param  float  monthly interest rate
 * @return float  denominator used to calculate monthly payment
 */


/**
 * Exception used for catching incomplete form input
 */
class IncompleteException extends Exception
{
}





/* --------------------------------------------------------------------- */
/* SOFTWARE LICENSE
/* --------------------------------------------------------------------- */
/*
	///// mortgage_calculator.php /////
	Copyright (c) 2002 David Tufts <http://davetufts.com> 
	All rights reserved.
	
	Redistribution and use in source and binary forms, with or without 
	modification, are permitted provided that the following conditions 
	are met:
	
	*	Redistributions of source code must retain the above copyright 
	    notice, this list of conditions and the following disclaimer.
	*	Redistributions in binary form must reproduce the above 
	    copyright notice, this list of conditions and the following 
	    disclaimer in the documentation and/or other materials 
	    provided with the distribution.
	*	Neither the name of David Tufts nor the names of its 
	    contributors may be used to endorse or promote products 
	    derived from this software without specific prior 
	    written permission.
	
	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND 
	CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, 
	INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
	MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
	DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS 
	BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
	EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
	TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
	DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 
	ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 
	OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 
	OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
	POSSIBILITY OF SUCH DAMAGE.
*/
?>